package com.example.mvp.Presenter;

import android.util.Log;

import com.example.mvp.Model.BaseModel;
import com.example.mvp.View.BaseView;
import com.trello.rxlifecycle2.LifecycleProvider;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;

public class BasePresenter<V extends BaseView,M extends BaseModel> implements RxPresenter<V>{
    //弱引用
   private WeakReference<V>mWeakReference;
   public V mView;
   private M model;
    @Override
    public void bindView(V v) {
        mWeakReference=new WeakReference<V>(v);
        if (mWeakReference!=null){
            mView=mWeakReference.get();

//            if (mWeakReference!=null){
//                Log.e("huage", "bindView: "+v.getClass() );
//                mView= (V) Proxy.newProxyInstance(mWeakReference.get().getClass().getClassLoader(), mWeakReference.get().getClass().getInterfaces(), new InvocationHandler() {
//                    @Override
//                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                        if (mWeakReference==null||mWeakReference.get()==null){
//                            return null;
//                        }
//                        return method.invoke(mWeakReference.get(),args);
//                    }
//                });
//            }
            initMode();
        }

    }

    private void initMode() {
        ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
        Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
        Class<M> modelClass = (Class<M>) actualTypeArguments[1];
        try {
            model=modelClass.newInstance();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }


    }

    public V getmView() {
        return mView;
    }

    @Override
    public void destoryView() {
        if (mWeakReference!=null){
            mWeakReference.clear();
            mWeakReference=null;
        }
        if (mView!=null){
            mView=null;
        }
    }

    @Override
    public LifecycleProvider getLifecycleProvider() {
        if (getmView()!=null){
            return (LifecycleProvider) mView;
        }
        return null;

    }

    public M getModel() {
        return model;
    }
}
